/**
 * create by young (young2f@outlook.com) on 2023/8/8
 */
'use strict';
const _ = require('lodash');
const emq = require('mqtt');
const devMqtt = {
    enable: true,
    url: 'tcp://www.iotmqtt.cn',
    port: 21883,
};
const {url, port} = devMqtt;

const qos = 0;
const opts = {port, qos};
const mqtt = emq.connect(url, opts);
mqtt.on('connect', packet => {
    console.log('IIOT平台连接成功!!!', url, port);
});

/**
 * mqtt订阅消息到达
 */
mqtt.on('message', (topic, message) => {
    console.log('MQTT消息到达', message);
    const json = _stringUtils.buffer2json(message);

});
mqtt.on('error', error => {
    console.log('IIOT平台连接 error', url);
});
mqtt.on('close', error => {
    console.log('IIOT平台连接 close', url);
});

mqtt.on('offline', error => {
    console.log('IIOT平台连接 offline', url);
});

function sendData(topic, payload) {
    if (mqtt && mqtt.connected) {
        const opt = {qos: 0, retain: false};
        if (typeof payload === 'object') {
            payload = JSON.stringify(payload);
        }
        mqtt.publish(topic, payload, opt, err => {
            if (err) {
                console.log('mqtt pub error', topic, err);
            }
        });
        console.log('send data', topic, payload);
        return
    }
    console.log('send data error', topic);
}

module.exports = {
    sendData
};
